package com.newdjk.newdoctor.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatButton;

import com.newdjk.newdoctor.BasActivity;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.dialog.CityChooseDialog;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.LocationUtils;
import com.newdjk.newdoctor.utils.LogUtils;
import com.newdjk.newdoctor.utils.MyCountDownTimer;
import com.newdjk.newdoctor.utils.SpUtils;
import com.newdjk.newdoctor.utils.StrUtil;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.okhttp.entity.AreaEntity;
import com.newdjk.okhttp.entity.BaseEntity;
import com.newdjk.okhttp.entity.LocationEntity;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class RegisterActivity extends BasActivity {


    private static final String TAG = "RegisterActivity";
    @BindView(R.id.tv_bd_code)
    TextView tvBdCode;
    @BindView(R.id.cb_agreement)
    CheckBox cbAgreement;
    @BindView(R.id.btn_register)
    AppCompatButton btnRegister;
    @BindView(R.id.input_user)
    EditText inputUser;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_name)
    EditText tvName;
    @BindView(R.id.tv_verfycode)
    EditText tvVerfycode;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_area_title)
    TextView tvAreaTitle;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    private MyCountDownTimer mcdt;
    private AreaEntity area;
    private String currentarea;

    private LocationEntity locationEntity;
    private int refisterType = 1;
    private String provinceID = "0";

    private String mProvinceName;
    private String mProvinceID;
    private String mcityName;
    private String mcityID;
    private String mAreaid;
    private String mAreaName;

    @Override
    public boolean IsShowBackIcon() {
        return true;
    }

    @Override
    protected String setTitle() {
        return "注册";
    }

    @Override
    protected int initViewResId() {
        return R.layout.activity_register;
    }

    @Override
    protected void initListener() {
        tvBdCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mcdt = new MyCountDownTimer(tvBdCode, 60000, 1000);
                requestCode();

            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });

        //选择地址
        tvLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CityChooseDialog.getInstance().showBottomSexDialog(RegisterActivity.this, provinceID + "", new CityChooseDialog.CitySelectListener() {

                    @Override
                    public void citySelectListener(String provinceName, String cityName, String areaName, String path) {
                        String[] list = path.split(",");
                        if (list.length == 5) {
                            mProvinceName = provinceName;
                            mProvinceID = list[2] + "";
                            mcityName = cityName;
                            mcityID = list[3] + "";
                            mAreaName = areaName;
                            mAreaid = list[4] + "";
                            currentarea = provinceName + cityName + areaName;
                            tvLocation.setText(currentarea);
                        } else {
                            mProvinceName = provinceName;
                            mProvinceID = list[2] + "";
                            mcityName = cityName;
                            mcityID = list[3] + "";
                            mAreaName = areaName;
                            mAreaid = "0";
                            currentarea = provinceName + cityName + areaName;
                            tvLocation.setText(currentarea);
                        }

                    }
                });
            }
        });

        tvAgreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(RegisterActivity.this,AgreementActivity.class);
                startActivity(intent);
            }
        });
    }

    private void register() {
        if (!cbAgreement.isChecked()) {
            ToastUtil.setToast("请确认已阅读用户协议");
            return;
        }
        if (TextUtils.isEmpty(tvName.getText().toString())) {
            if (refisterType == 0) {
                ToastUtil.setToast("诊所名称不能为空");
                return;
            } else {
                ToastUtil.setToast("药店名称不能为空");
                return;
            }

        }
        if (TextUtils.isEmpty(inputUser.getText().toString())) {
            ToastUtil.setToast("手机号不能为空");
            return;
        }
        if (TextUtils.isEmpty(tvVerfycode.getText().toString())) {
            ToastUtil.setToast("验证码不能为空");
            return;
        }

        if (TextUtils.isEmpty(currentarea)) {
            ToastUtil.setToast("定位失败，请手动选择区域");
            return;
        }


        NetServices.Factory.getService().ClinicRegister(
                tvName.getText().toString(),
                inputUser.getText().toString(),
                tvVerfycode.getText().toString(),
                mProvinceID,
                mProvinceName,
                mcityID,
                mcityName,
                mAreaid,
                mAreaName,
                "0",
                currentarea,
                //注册机构类型。0诊所；1药房
                refisterType + ""

        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver(RegisterActivity.this, false) {
                    @Override
                    protected void onSuccees(BaseEntity t) throws Exception {
                        ToastUtil.setToast("注册成功");
                        SpUtils.put(Contants.Password, "");
                        SpUtils.put(Contants.isPasswordlogin, false);
                        SpUtils.put(Contants.Token, "");
                        SpUtils.put(Contants.userName, StrUtil.getString(inputUser));
                        Intent intent = new Intent(RegisterActivity.this, RegisterSuccessActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                        ToastUtil.setToast(erroressage + "");
                        mcdt.clear();
                    }
                });


    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        LocationUtils.getinstanse().initlocation(RegisterActivity.this, new LocationUtils.locationStatusListener() {
            @Override
            public void locationSuccess(String data, String location, String province, String city, String area) {
                //如果历史不为空，并且定位到了其他城市
                currentarea = data;
                RegisterActivity.this.mProvinceName = province;
                RegisterActivity.this.mcityName = city;
                RegisterActivity.this.mAreaName = area;
                tvLocation.setText(data);
                // getLocation(location);
                getProvinceLocation(area);
                LocationUtils.getinstanse().stopLocation();
            }

            @Override
            public void locationFailed(String data) {
                ToastUtil.setToast(data);
                LocationUtils.getinstanse().stopLocation();
            }
        });
        refisterType = getIntent().getIntExtra(Contants.refisterType, 0);
        if (refisterType == 0) {
            tvTitle.setText("诊所名称");
            tvAreaTitle.setText("诊所区域");
        } else {
            tvTitle.setText("药店名称");
            tvAreaTitle.setText("药店区域");
        }
    }

    private void getProvinceLocation(String province) {

        NetServices.Factory.getService().QueryAreaByName(province
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<AreaEntity>(RegisterActivity.this, false) {
                    @Override
                    protected void onSuccees(BaseEntity<AreaEntity> t) throws Exception {
                        area = t.getData();
                        String[] list = area.getPath().split(",");
                        mProvinceID = list[2];
                        mcityID = list[3];
                        mAreaid = list[4];

                    }
                });
    }

    private void getLocation(String location) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("Location", location);
        NetServices.Factory.getService().GetAddressByLocation(paramsMap
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<LocationEntity>(RegisterActivity.this, false) {
                    @Override
                    protected void onSuccees(BaseEntity<LocationEntity> t) throws Exception {
                        LogUtils.d(TAG, t.toString());
                        locationEntity = t.getData();
                    }
                });


    }


    private void requestCode() {
        if (!StrUtil.isMobile(StrUtil.getString(inputUser))) {
            ToastUtil.setToast("手机号码格式不正确");
        } else {
            NetServices.Factory.getService().SendMobileCode(StrUtil.getString(inputUser)
            ).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseComPleteObserver(RegisterActivity.this) {
                        @Override
                        protected void onSuccees(BaseEntity t) throws Exception {
                            LogUtils.d(TAG, t.toString());
                            if (t.getCode() == 0) {
                                mcdt.start();
                            }
                            ToastUtil.setToast("发送成功");
                        }
                    });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
